package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.ServiceItemMapper;
import cn.wolfcode.car.business.query.ServiceItemQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BaseException;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import com.sun.deploy.panel.ITreeNode;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.bcel.generic.NEW;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class ServiceItemServiceImpl implements IServiceItemService {

    @Autowired
    private ServiceItemMapper serviceItemMapper;
    @Autowired
    private ICarPackageAuditService carPackageAuditService;
    @Autowired
    private IBpmnInfoService bpmnInfoService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;


    @Override
    public TablePageInfo<ServiceItem> query(ServiceItemQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<ServiceItem>(serviceItemMapper.selectForList(qo));
    }


    @Override
    public void save(ServiceItem serviceItem) {
        ServiceItem item = new ServiceItem();
        item.setName(serviceItem.getName());
        item.setOriginalPrice(serviceItem.getOriginalPrice());
        item.setDiscountPrice(serviceItem.getDiscountPrice());
        item.setCarPackage(serviceItem.getCarPackage());
        item.setInfo(serviceItem.getInfo());
        item.setServiceCatalog(serviceItem.getServiceCatalog());
        item.setCreateTime(new Date());
        item.setIsDelete(0);
        if (ServiceItem.CARPACKAGE_YES.equals(item.getCarPackage())){
            //如果是套餐,则设置审核状态为初始化
            item.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
        }else {
            //如果不是套餐,则设置审核状态为无需审核
            item.setAuditStatus(ServiceItem.AUDITSTATUS_NO_REQUIRED);
        }
        serviceItemMapper.insert(item);
    }


    @Override
    public void update(ServiceItem serviceItem) {
        ServiceItem item = this.get(serviceItem.getId());
        //处于上架状态或者审核中,不能修改
        if (ServiceItem.SALESTATUS_ON.equals(item.getSaleStatus())
                || ServiceItem.AUDITSTATUS_AUDITING.equals(item.getAuditStatus())) {
            throw new BaseException("非法操作");
        }
        //套餐(非套餐无需审核),审核通过,需把状态设置为初始化
        if (ServiceItem.AUDITSTATUS_APPROVED.equals(item.getAuditStatus())) {
            item.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
        }
        //把前台属性设置到当前对象中
        item.setName(serviceItem.getName());
        item.setOriginalPrice(serviceItem.getOriginalPrice());
        item.setDiscountPrice(serviceItem.getDiscountPrice());
        item.setInfo(serviceItem.getInfo());
        item.setServiceCatalog(serviceItem.getServiceCatalog());
        serviceItemMapper.updateByPrimaryKey(item);
    }

    @Override
    public void deleteBatch(Long id) {
            serviceItemMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<ServiceItem> list() {
        return serviceItemMapper.selectAll();
    }

    @Override
    public ServiceItem get(Long id) {
        return serviceItemMapper.selectByPrimaryKey(id);
    }

    @Override
    public void saleOn(Long id) {
        //合理化校验
        ServiceItem item = this.get(id);
        if (item!=null) {
            //如果处于上架状态,不需要操作
            if (ServiceItem.SALESTATUS_ON.equals(item.getSaleStatus())) {
                return;
            }
            //如果是套餐且处于非通过审核,不允许进行上架操作
            if (ServiceItem.CARPACKAGE_YES.equals(item.getCarPackage())
                    && !ServiceItem.AUDITSTATUS_APPROVED.equals(item.getAuditStatus())) {
                    throw new BaseException("未审核通过的套餐不允许上架");
            }
            //其他情况都可以上架
            serviceItemMapper.updateSaleStatus(id,ServiceItem.SALESTATUS_ON);
        }
        }

    @Override
    public void saleOff(Long id) {
        serviceItemMapper.updateSaleStatus(id,ServiceItem.SALESTATUS_OFF);
    }

    @Override
    public void startAudit(Long id, Long bpmnInfoId, Long director, Long finance, String info) {
        ServiceItem serviceItem = this.get(id);
        //进行合理化校验
        if (!ServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage())) {
            throw new BusinessException("非法操作");
        }
        //说明是套餐
        if (ServiceItem.AUDITSTATUS_AUDITING.equals(serviceItem.getAuditStatus()) ||        //处于审核中
                ServiceItem.AUDITSTATUS_APPROVED.equals(serviceItem.getAuditStatus())       //审核通过
        ){
            throw new BusinessException("非法操作");
        }
        //封装CarPackageAudit对象
        CarPackageAudit audit = new CarPackageAudit();
        audit.setServiceItemId(serviceItem.getId());
        audit.setServiceItemName(serviceItem.getName());
        audit.setServiceItemPrice(serviceItem.getDiscountPrice());
        audit.setServiceItemInfo(serviceItem.getInfo());
        audit.setCreator(ShiroUtils.getUserId().toString());//创建人
        audit.setBpmninfoId(bpmnInfoId);    //BpmnInfo的ID
        audit.setInfo(info);
        audit.setCreateTime(new Date());
        carPackageAuditService.save(audit);//保存到数据库中,回填ID
        //查询bpmnInfo
        BpmnInfo bpmnInfo = bpmnInfoService.get(bpmnInfoId);
        //获取流程定义Key
        String definitionKey = bpmnInfo.getActProcessKey();
        //业务表示BusinessKey
        String businessKey = audit.getId().toString();
        //储存流程变量
        Map<String,Object> params = new HashMap<>();
        params.put("director",director);
        if (finance!=null) {
            params.put("finance",finance);
        }
        params.put("discountPrice",serviceItem.getDiscountPrice().longValue());//将Bigdecimal转成Long类型
        //启动流程获取到流程实例对象
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(definitionKey, businessKey, params);
        //流程审核对象关联流程实例对象
        audit.setInstanceId(processInstance.getId());
        //查询当前流程实例目前处于哪个任务中?
        Task currentTask = taskService.createTaskQuery()
                .processInstanceId(processInstance.getId())
                .singleResult();
        //获取到当前流程运行的节点,获取到这个节点处理人
        audit.setAuditorId(Long.parseLong(currentTask.getAssignee()));
        carPackageAuditService.update(audit);
        //更新服务单项的状态
        serviceItemMapper.changeAuditStatus(serviceItem.getId(),ServiceItem.AUDITSTATUS_AUDITING);
    }

    @Override
    public void changeStatus(Long serviceItemId, Integer status) {
        serviceItemMapper.changeAuditStatus(serviceItemId,status);
    }
}

